package org.seven.cpcrkapp.util;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.seven.cpcrkapp.constant.GlobalContants;
import org.seven.cpcrkapp.model.Result;

public abstract class HttpUtils {
    public static String get(String url) throws Exception {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(WebAppUtils.getURL() + url).build();
            Response response = client.newCall(request).execute();
            String data = response.body().string();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

    public static Result getResult(String url) throws Exception {
        try {
            String data = get(url);
            Result result = JsonUtils.getValue(data, Result.class);
            if (!result.isSuccess()) {
                throw new Exception(result.getMsg());
            }
            return result;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    public static String post(String url, String json) throws Exception {
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new FormEncodingBuilder().add("json", json).build();
            Request request = new Request.Builder().url(WebAppUtils.getURL() + url).post(requestBody).build();
            Response response = client.newCall(request).execute();
            String data = response.body().string();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
    }

    public static Result postResult(String url, String json) throws Exception {
        try {
            String data = post(url, json);
            Result result = JsonUtils.getValue(data, Result.class);
            if (!result.isSuccess()) {
                throw new Exception(result.getMsg());
            }
            return result;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }
}